package xyz.yeidi.dao.impl;

import xyz.yeidi.dao.api.FoodDao;
import xyz.yeidi.pojo.Food;
import xyz.yeidi.utils.ConnUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author JIP
 * @Date 2021-08-03 15:01
 * @Version 1.0
 * @Describe :
 */
public class FoodDaoImpl implements FoodDao {
    @Override
    public List<Food> getFoodsByBusiness(Integer businessId) throws Exception {
        String sql = "select foodId,foodName, foodExplain, foodImg, foodPrice from food where businessId = ?";
        Connection conn = ConnUtils.getConnection();
        List<Food> list = new ArrayList<>();
        Food food = null;
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setObject(1,businessId);
        ResultSet rs = ps.executeQuery();

        while(rs.next()){
            food = new Food();
            food.setFoodId(rs.getInt(1));
            food.setFoodName(rs.getString(2));
            food.setFoodExplain(rs.getString(3));
            food.setFoodImg(rs.getString(4));
            food.setFoodPrice(rs.getFloat(5));
            list.add(food);
        }
        ConnUtils.close(rs,ps);
        return list;
    }

    @Override
    public Food getFoodById(Integer id) throws Exception {
        String sql = "select foodName, foodExplain, foodImg, foodPrice from food where foodId = ?";
        Connection conn = ConnUtils.getConnection();
        Food food = null;
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setObject(1,id);
        ResultSet rs = ps.executeQuery();

        if(rs.next()){
            food = new Food();
            food.setFoodId(id);
            food.setFoodName(rs.getString(1));
            food.setFoodExplain(rs.getString(2));
            food.setFoodImg(rs.getString(3));
            food.setFoodPrice(rs.getFloat(4));
        }
        ConnUtils.close(rs,ps);
        return food;
    }

    @Override
    public List<Food> searchFoodsByName(String foodName) throws Exception {
        String sql = "select foodId,foodName, foodExplain, foodImg, foodPrice from food where foodName like ?";
        Connection conn = ConnUtils.getConnection();
        List<Food> list = new ArrayList<>();
        Food food = null;
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setObject(1,"%"+foodName+"%");
        ResultSet rs = ps.executeQuery();

        while(rs.next()){
            food = new Food();
            food.setFoodId(rs.getInt(1));
            food.setFoodName(rs.getString(2));
            food.setFoodExplain(rs.getString(3));
            food.setFoodImg(rs.getString(4));
            food.setFoodPrice(rs.getFloat(5));
            list.add(food);
        }
        ConnUtils.close(rs,ps);
        return list;
    }
}
